<?php


namespace console\controllers;


use Faker\Factory;
use workflow\models\File;
use yii\console\Controller;

class SaveFileController extends Controller
{
    public string  $filename;

    public function init()
    {
        parent::init();

        $this->filename = dirname(dirname(__DIR__)).'/console/tests/unit/fixtures/data/test.file.txt';
    }

    public function actionIndex3()
    {

        $start = memory_get_usage();

        $func = function () {
            $file = fopen($this->filename, "r");
            while (!feof($file)) {
                yield substr(fgets($file), 3);
            }
            fclose($file);
        };

        foreach ($func() as $item) {

        }

        $end = memory_get_usage();

        echo $end - $start;
    }

    public function actionIndex()
    {

        $start = memory_get_usage();

        $contents = file_get_contents($this->filename);

        $contents = explode("\n", $contents);

        $rows = [];

        $faker = Factory::create();
        foreach ($contents as $item) {
            $date = $faker->dateTimeThisYear()->format('Y-m-d H:i:s');
            $rows[] = [
                'path' => substr($item, 3),
                'title' => substr($item, strrpos($item, '/') + 1),
                'created_at' => $date,
                'updated_at' => $date,
            ];
        }

        $res = \Yii::$app->db->createCommand()
            ->batchInsert('file', ['path', 'title', 'created_at', 'updated_at'], $rows)
            ->execute();

        $end = memory_get_usage();

        echo $end - $start;
    }

    /**
     * 这个居然是内存用的最少的~~~
     */
    public function actionIndex2()
    {

        $start = memory_get_usage();

        $file = fopen($this->filename, "r");
        while (!feof($file)) {
            $item = substr(fgets($file), 3);
        }
        fclose($file);

        $end = memory_get_usage();
        echo $end - $start;
    }
}